package com.hua.api.core.framework.config.scurity;

import com.alibaba.fastjson.JSONObject;
import com.hua.api.core.framework.util.crypto.ByteHelper;
import com.hua.api.core.framework.annotation.TokenCheck;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

@Slf4j
public class TokenHelper {
    public static final String FIELD_NAME = "userpass";
    public static final String KEY = "dfyfhqs9";
    public static final String ALGORITHM = "DES";
    public static final String X_WMALL_Authorization="Authorization";//Authorization
    public static final String Hua_User_Agent = "Hua-User-Agent";
    public static final String Hua_Nonce = "Hua-Nonce";
    public static final String Hua_Appkey = "Hua-Appkey";
    public static final String Hua_Timestame = "Hua-Timestame";
    public static final String Hua_Signature = "Hua-Signature";


//    public static void main(String[] args){
//        JSONObject json = new JSONObject();
//        json.put("id","1");
//        json.put("source","admin");
//        json.put("roleId","888");
//        System.out.println(createToken(json.toJSONString()));
//    }


//    public static String createToken(Integer userId,String source,Integer roleId, String phoneNumber){
//        String cookie = null;
//        try{
//            JSONObject data = new JSONObject();
//            data.put("id",userId);
//            data.put("source",source);
//            data.put("roleId",roleId);
//            data.put("phoneNumber",phoneNumber);
//            data.put("timestamp",(System.currentTimeMillis() / 1000));
//            byte[] contentBytes = data.toJSONString().getBytes();
//            byte[] keyBytes = KEY.getBytes();
//            byte[] cookieBytes = ByteHelper.encryptData(contentBytes, keyBytes);
//            cookie = ByteHelper.byte2hex(cookieBytes);
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//        return cookie;
//    }



    /**
     * token 格式
     * {
     *     id: 0, // 用户id
     *     source: 'store', // store eladmin
     *     roleId: 999, // 用户角色
     *     timestamp:xxxxx //时间戳
     * }
     * */
    public static boolean checkToken(String token, TokenCheck check) throws ApiError {

        token = token.replace("Bearer ","");
        try{
            byte[] cookieBytes = ByteHelper.hex2byte(token);
            byte[] decodedBytes = ByteHelper.decryptData(cookieBytes, KEY.getBytes());
            String decodedString = new String(decodedBytes);
            JSONObject data = JSONObject.parseObject(decodedString);
            Integer userId = data.getInteger("id");
            String source = data.getString("source");
            String roleId = data.getString("roleId");
            if(StringUtil.isEmptys(userId,source,roleId)){
                throw ApiError.Type.TOKEN_ERROR.toException("Authorization 状态异常！");
            }
            if(null!=check){

                // 验证 请求项目 eladmin store
                if(!StringUtil.isEmpty(check.source()) && check.source().length>0 &&  !exist(check.source(),source)){
                    log.info("source={}",source);
                    throw ApiError.Type.TOKEN_ERROR.toException("Authorization 状态异常！source条件判断错误");
                }

                // 验证roleId
                if(!StringUtil.isEmpty(check.roleId()) && check.roleId().length>0 && !StringUtil.contains(check.roleId(),roleId)){
                    throw ApiError.Type.TOKEN_ERROR.toException("Authorization 状态异常！");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw ApiError.Type.TOKEN_ERROR.toException(e.getMessage());
        }
        return true;
    }

    public static boolean exist(String[] sources,String source){
        for(String e: sources){
            if(StringUtil.equals(e,source)){
                return true;
            }
        }
       return false;
    }



    public static String createToken(String src){

        if(StringUtil.isEmpty(src)){
            return null;
        }

        String token="";
        try{
            byte[] contentBytes = src.getBytes();
            byte[] keyBytes = KEY.getBytes();
            byte[] cookieBytes = ByteHelper.encryptData(contentBytes, keyBytes);
            token = ByteHelper.byte2hex(cookieBytes);
        }catch(Exception e){
            e.printStackTrace();
        }
        return token;
    }


    public static UserInfo getUserInfo(){
        //HttpServletRequest request = (HttpServletRequest) RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(X_WMALL_Authorization);
        if(!StringUtil.isEmpty(token)){
            token = token.replace("Bearer ","");
            try{
                byte[] cookieBytes = ByteHelper.hex2byte(token);
                byte[] decodedBytes = ByteHelper.decryptData(cookieBytes, KEY.getBytes());
                String decodedString = new String(decodedBytes);
                JSONObject data = JSONObject.parseObject(decodedString);
                Integer userId = data.getInteger("id");
                String source = data.getString("source");
                String roleId = data.getString("roleId");
                UserInfo user = new UserInfo();
                user.setRoleId(roleId);
                user.setUserId(userId);
                user.setSource(source);
                return user;
            }catch (Exception e){
                e.printStackTrace();
                throw ApiError.Type.TOKEN_ERROR.toException(e.getMessage());
            }


        }


        UserInfo user = new UserInfo();
        user.setUserId(-1);
        return user;

    }




    public static String parseToken(String src){

        if(StringUtil.isEmpty(src)){
            return null;
        }
        try{
            byte[] cookieBytes = ByteHelper.hex2byte(src);
            byte[] decodedBytes = ByteHelper.decryptData(cookieBytes, KEY.getBytes());
            String decodedString = new String(decodedBytes);
            return decodedString;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
